#include <iostream>
// #include "Log.hpp"
#include <memory>
#include <vector>
#include "UdpServer.hpp"

void Usage(std::string proc)
{
    std::cout << "\n\r Usage: " << proc << " port[1024+]\n"
              << std::endl;
}

std::string Handler(const std::string &info,const std::string& clientip,const uint16_t& clientport)
{
    std::cout << "[" << clientip << ":" << clientport << "]# " << info << std::endl;
    std::string res = "Server get a message: ";
    res += info;
    std::cout << res << std::endl;
    return res;
}

bool SafeCheck(const std::string &cmd)
{
    int safe = false;
    std::vector<std::string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "top",
        "while"
    };
    for(auto &word : key_word)
    {
        auto pos = cmd.find(word);
        if(pos != std::string::npos) return false;
    }

    return true;
}

std::string ExcuteCommand(const std::string &cmd)
{
    if(!SafeCheck(cmd)){return "bad man";}

    FILE* fp = popen(cmd.c_str(),"r");
    if(nullptr == fp)
    {
        perror("popen");
        return "error";
    }
    std::string result;
    char buffer[4096];
    while(true)
    {
        char *ok = fgets(buffer,sizeof(buffer),fp);//并在写入的缓冲区末尾自动添加一个空字符（null terminator）\0来标记字符串的结束。
        if (ok == nullptr) {break;}
        result += buffer;
    }
    pclose(fp);
    return result;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<UdpServer> svr(new UdpServer(port));

    svr->Init();
    svr->Run(Handler);
    // Log lg;
    // lg.Enable(Onefile);
    // lg(Fatal, "socket create error, sockfd: %d\n", 11);
    // lg(Debug, "socket create error, sockfd: %d\n", 12);
    // lg(Info, "socket create error, sockfd: %d\n", 13);
    // lg(Warning, "socket create error, sockfd: %d\n", 14);
    // lg(Error, "socket create error, sockfd: %d\n", 15);
    return 0;
}